import Vue from 'vue'
import Vuex from 'vuex'
import $mConstDataConfig from '@/config/constData.config';
import $mSettingConfig from '@/config/setting.config';

Vue.use(Vuex)

/**
 * 页面使用：import { mapState, mapMutations } from 'vuex'  引入
 * computed: mapState(['authLogin', 'userInfo'])
 * methods: ...mapMutations(['login']),
 * 实时更新用户状态函数: onMain(user) {this.login(user)},
 */

const THEMECOLOR = uni.getStorageSync('themeColor');
const GLOBALCONFIG = uni.getStorageSync('globalConfig') || {};
const APPCONFIG = uni.getStorageSync('appConfig') || {};

const store = new Vuex.Store({
	state: { // 存放状态
		authLogin: false, // 登录状态
		userInfo: {},
		themeColor: THEMECOLOR, // 主题
		globalConfig: GLOBALCONFIG, // 全局配置
		appConfig: APPCONFIG
	},
	getters: {
		// 全局配置
		themeColor: state => {
			let theme = state.themeColor;
			if (!theme) {
				theme = $mConstDataConfig.themeList.filter((item) => item.name === ($mSettingConfig
					.styleType || 'cz'))[0];
			}
			return theme;
		},
		// 全局配置
		globalConfig: state => {
			return state.globalConfig;
		}
	},
	mutations: {
		login(state, user) { // 登录
			state.authLogin = true;
			state.userInfo = user || '';
		},
		logout(state) { // 退出
			state.authLogin = false;
			uni.removeStorage({
				key: 'userInfo'
			})
			uni.removeStorage({
				key: 'authLogin'
			})
			let pages = getCurrentPages();
			let currPage = pages[pages.length - 1]; // 当前页面
			let prevPage = pages[pages.length - 2]; // 上一页面
			if (prevPage) {
				uni.navigateBack()
			} else {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		},
		invalidToken(state) {
			state.authLogin = false;
			uni.removeStorage({
				key: 'userInfo'
			})
			uni.removeStorage({
				key: 'authLogin'
			})
		},
		setThemeColor(state, val) {
			state.themeColor = val;
			uni.setStorageSync('themeColor', val);
		},
		setConfig(state, val) {
			state.appConfig = val;
			uni.setStorageSync('appConfig', val);
		}
	},
	actions: {
		invalidToken(context) {
			context.commit('invalidToken')
		}
	}
})

export default store